<template>
  <div class="teacher-mbti-container">
    <el-card class="mbti-card">
      <template #header>
        <div class="card-header">
          <div class="header-center">
            <span class="header-title">班级学生MBTI统计</span>
            <el-select
              v-model="currentClassId"
              placeholder="请选择班级"
              @change="handleClassChange"
              style="width: 250px; margin-left: 15px;"
            >
              <el-option
                v-for="classItem in classOptions"
                :key="classItem.classId"
                :label="classItem.className"
                :value="classItem.classId"
              />
            </el-select>
          </div>
          <div class="header-right">
            <div class="user-info">
              <el-icon><User /></el-icon>
              <span class="user-name">用户: {{userInfo.username}}</span>
            </div>
            <el-button 
              type="danger" 
              plain 
              size="small" 
              @click="handleLogout"
              class="logout-btn"
            >
              <el-icon><SwitchButton /></el-icon>
              <span>退出登录</span>
            </el-button>
          </div>
        </div>
      </template>

      <!-- MBTI统计图表 -->
      <div class="mbti-chart-container" v-if="mbtiStats && Object.keys(mbtiStats).length > 0">
        <div class="chart-wrapper">
          <div ref="chartRef" style="width: 100%; height: 400px;"></div>
        </div>
      </div>
      <el-empty v-else description="暂无MBTI统计数据" />

      <!-- 学生MBTI列表 -->
      <el-table
        :data="classStudents"
        v-loading="loading"
        border
        stripe
        style="width: 100%; margin-top: 20px;"
        empty-text="暂无学生数据"
      >
        <el-table-column prop="studentNumber" label="学号" width="120" align="center" />
        <el-table-column prop="studentName" label="姓名" width="100" align="center" />
        <el-table-column prop="mbtiType" label="MBTI类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getMbtiColor(row.mbtiType)" effect="dark">
              {{ row.mbtiType || '未测试' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="testTime" label="最新测试时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.testTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userInfo = ref(JSON.parse(localStorage.getItem('xm-pro-user')) || {})

// 图表DOM引用和实例
const chartRef = ref(null)
let chartInstance = null

// 数据状态
const loading = ref(false)
const currentClassId = ref('')
const classOptions = ref([]) // 所有班级选项
const allClassStudents = ref({}) // 按班级ID存储的学生数据 { classId1: [...], classId2: [...] }
const classStudents = ref([]) // 当前班级的学生数据

// 计算MBTI统计
const mbtiStats = computed(() => {
  const stats = {}
  classStudents.value.forEach(student => {
    if (student.mbtiType) {
      stats[student.mbtiType] = (stats[student.mbtiType] || 0) + 1
    }
  })
  return stats
})

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || !mbtiStats.value) return
  
  const options = {
    title: {
      text: 'MBTI类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: Object.keys(mbtiStats.value)
    },
    series: [
      {
        name: 'MBTI分布',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.entries(mbtiStats.value).map(([name, value]) => ({
          name,
          value,
          itemStyle: { color: getMbtiChartColor(name) }
        }))
      }
    ]
  }
  
  chartInstance.setOption(options)
}

// MBTI颜色映射
const getMbtiColor = (type) => {
  if (!type) return 'info'
  const colorMap = {
    INTJ: 'success',
    INTP: 'success',
    ENTJ: 'warning',
    ENTP: 'warning',
    INFJ: 'danger',
    INFP: 'danger',
    ENFJ: 'primary',
    ENFP: 'primary',
    ISTJ: '',
    ISFJ: '',
    ESTJ: '',
    ESFJ: '',
    ISTP: 'info',
    ISFP: 'info',
    ESTP: 'info',
    ESFP: 'info'
  }
  return colorMap[type] || 'info'
}

// 图表颜色映射
const getMbtiChartColor = (type) => {
  const colorMap = {
    INTJ: '#67C23A',
    INTP: '#95D475',
    ENTJ: '#E6A23C',
    ENTP: '#F0C78A',
    INFJ: '#F56C6C',
    INFP: '#F89898',
    ENFJ: '#409EFF',
    ENFP: '#7AB8FF',
    ISTJ: '#909399',
    ISFJ: '#B1B3B8',
    ESTJ: '#A6A9AD',
    ESFJ: '#C8C9CC',
    ISTP: '#5D9CEC',
    ISFP: '#8BB8F1',
    ESTP: '#4CB3D6',
    ESFP: '#7AC5E4'
  }
  return colorMap[type] || '#909399'
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 获取教师所教的班级列表
const fetchTeacherClasses = async () => {
  try {
    loading.value = true
    const res = await request.get('/class/selectAll', {
      params: {
        teacherId: userInfo.value.userId
      }
    })
    
    if (res && res.code === '200') {
      classOptions.value = res.data || []
      
      // 如果有班级，默认选择第一个班级
      if (classOptions.value.length > 0) {
        currentClassId.value = classOptions.value[0].classId
        await fetchClassMBTI(currentClassId.value)
      }
    } else {
      ElMessage.error(res.msg || '获取班级列表失败')
    }
  } catch (error) {
    console.error('获取班级列表失败:', error)
    ElMessage.error('获取班级列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取班级学生MBTI数据
const fetchClassMBTI = async (classId) => {
  try {
    loading.value = true
    
    // 如果已有缓存数据，直接使用
    if (allClassStudents.value[classId]) {
      classStudents.value = allClassStudents.value[classId]
      updateChartData()
      return
    }
    
    const res = await request.get('/mbtitest/class-mbti', {
      params: { classId }
    })
    
    if (res && res.code === '200') {
      const students = res.data || []
      // 缓存数据
      allClassStudents.value[classId] = students
      classStudents.value = students
      
      updateChartData()
    } else {
      ElMessage.error(res.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取MBTI数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 更新图表数据
const updateChartData = () => {
  nextTick(() => {
    if (!chartInstance) {
      initChart()
    } else {
      updateChart()
    }
  })
}

// 班级切换处理
const handleClassChange = (classId) => {
  if (classId) {
    fetchClassMBTI(classId)
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除用户信息
    localStorage.removeItem('xm-pro-user')
    // 跳转到登录页
    router.push('/login')
    ElMessage.success('退出成功')
  }).catch(() => {
    // 取消操作
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchTeacherClasses()
  
  // 窗口大小变化时重新调整图表大小
  window.addEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
})

// 组件卸载时移除事件监听和销毁图表
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>

<style scoped>
.teacher-mbti-container {
  padding: 20px;
}

.mbti-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(90deg, #f8f9fa, #ffffff);
  border-radius: 10px 10px 0 0;
}

.header-center {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
  padding: 5px 12px;
  background-color: #f5f7fa;
  border-radius: 16px;
}

.user-info .el-icon {
  font-size: 16px;
  color: #409eff;
}

.user-name {
  font-weight: 500;
}

.logout-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  border-radius: 16px;
  padding: 8px 15px;
}

.logout-btn .el-icon {
  font-size: 14px;
}

.mbti-chart-container {
  margin: 20px 0;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>